package org.xuyuji.demo.xstream.bean;

import java.util.ArrayList;
import java.util.List;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamImplicit;

/**
 * 
 * @XStreamAlias 设置序列化时的别名，如果不设置默认为类全名，这里是org.xuyuji.demo.xstream.Person
 * @author Xuyuji
 *
 */
@XStreamAlias("Person")
public class Person {

	@XStreamAlias("Name")
	private String name;
	
	@XStreamAlias("Addresses")
	private Address address;
	
	@XStreamAlias("Friends")
	private List<Friend> list = new ArrayList<Friend>();
	
	public Person() {
	}
	
	/**
	 * public 是为了在外部使用
	 * static 是为了避免序列化时出现outer-class节点，如果没有xstream会添加一个outer-class节点。
	 * @XStreamImplicit 根据设置的名称itemFieldName迭代容器
	 * @author Xuyuji
	 *
	 */
	public static class Address{
		
		@XStreamImplicit(itemFieldName="Address")
		private List<String> address = new ArrayList<String>();

		public List<String> getAddress() {
			return address;
		}

		public void setAddress(String address) {
			this.address.add(address);
		}
		
		public String toString(){
			return "" + address;
		}
	}
	
	/**
	 * 不设置别名就使用变量名,如这里的id
	 * @XStreamAsAttribute 讲该变量设置为节点的属性，而不是节点的下一级节点
	 * @author Xuyuji
	 *
	 */
	@XStreamAlias("Friend")
	public static class Friend{
		
		@XStreamAsAttribute
		private int id;
		
		@XStreamAlias("Name")
		private String name;

		public int getId() {
			return id;
		}

		public void setId(int id) {
			this.id = id;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}
		
		public String toString(){
			StringBuilder sb = new StringBuilder();
			
			sb.append("{").append("id:").append(id).append(",");
			sb.append("name:").append(name).append("}");
			
			return sb.toString();
		}
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}

	public List<Friend> getList() {
		return list;
	}

	public void setList(Friend friend) {
		this.list.add(friend);
	}
	
	public String toString(){
		StringBuilder sb = new StringBuilder();
		
		sb.append("name:").append(name).append(",");
		sb.append("addresses:").append(address).append(",");
		sb.append("friends:").append(list);
		
		return sb.toString();
	}
}
